package nancal.mp.service.jenkins.publish

import nancal.mp.db.mongo.GitServerTypeEnum
import nancal.mp.db.mongo.entity.dev.GitServer
import nancal.mp.db.mongo.entity.dev.JenkinsLog
import nancal.mp.db.mongo.mor
import nancal.mp.service.jenkins.JenkinsPublishJob
import nbcp.base.extend.HasValue
import nbcp.base.utils.UrlUtil
import nbcp.myoql.db.mongo.queryById


/**
 * @return  带用户名密码的下载地址,  http://用户名:密码@server/abc  增加部分为： 用户名:密码@
 */
fun JenkinsLog.getGitUserAndPasswordUrl(gitServer: GitServer): String {
    var url = this.gitData?.url;
    if (url == null) {
        throw RuntimeException("找不到Git数据")
    }
    var sects = url.split("://");

    return sects.first() + "://" + "${gitServer.userName}:${gitServer.password}@" + sects[1]
}

fun JenkinsLog.getAccessTokenUrl(accessToken: String): String {
    var url = this.gitData?.url;
    if (url == null) {
        throw RuntimeException("找不到Git数据")
    }
    var sects = url.split("://");

    return sects.first() + "://" + "${accessToken}@" + sects[1]
}

fun JenkinsPublishJob.j_start_job(): String {
    return """ 
echo "curl -o ${buildStartShell} -s  -w  %{http_code} --max-time 6 --retry 3  ${appDeploySetting.mpIntegrationApiUrl}/ops/jenkins/start-job/${this.task.id}?admin-token=${UrlUtil.encodeURIComponent(appDeploySetting.adminToken)}"
code=＄(curl -o ${buildStartShell} -s  -w  %{http_code} --max-time 6 --retry 3 "${appDeploySetting.mpIntegrationApiUrl}/ops/jenkins/start-job/${this.task.id}?admin-token=${UrlUtil.encodeURIComponent(appDeploySetting.adminToken)}" )

if [ "＄code" == "000" ]; then
    echo "网络错误，请重试！"
    exit 3;
elif [ "＄code" != "200" ]; then
    echo -e "\n"`date "+%Y-%m-%d %H:%M:%S"` '启动Job错误!!! 返回: ＄code'
  
    exit 1 
fi

cat ${buildStartShell}

echo -e "\n"`date "+%Y-%m-%d %H:%M:%S"` 'start-job'
source ${buildStartShell}  && start-job

""".replace("＄", "$")
}

fun JenkinsPublishJob.j_get_program_code(): String {

    var gitData = this.task.gitData;

    if (gitData == null) {
        var zipFile = this.task.sourceData?.zipFile;
        if (zipFile == null || zipFile.url.isEmpty()) {
            throw RuntimeException("找不到源码数据")
        }

        return """
sh '''#!/usr/bin/env bash
echo "下载源码并解压"
echo "wget  -q ${zipFile.url} -O  code.zip "
wget  -q ${zipFile.url} -O  code.zip 
echo "unzip -q -o  -d ./code code.zip "
unzip -q -o  -d ./code code.zip 
'''
"""
    }


    var gitServer = mor.dev.gitServer.queryById(gitData.server.id).toEntity()!!

    if (gitData.accessToken.HasValue) {

        var at = "";

        if (gitServer.gitServerType == GitServerTypeEnum.Gitlab) {
            at = "x-access-token:" + gitData.accessToken
        } else {
            at = gitData.accessToken;
        }


        return """
sh '''#!/usr/bin/env bash
git clone --depth=1  --single-branch -b ${this.task.buildInfo.gitBranch} ${
            this.task.getAccessTokenUrl(at)
        }
${this.appDeploySetting.sudo} mv ${gitData.path.split("/").last().split(".").first()} code
'''
"""
    } else if (gitServer.jenkinsCredential.HasValue) {
        return """
dir('code') {
    git branch: '${this.task.buildInfo.gitBranch}', changelog: false, credentialsId: '${gitServer.jenkinsCredential}', poll: false, url: '${gitData.url}'
}
"""
    } else if (gitServer.userName.HasValue) {
        return """
sh '''#!/usr/bin/env bash
git clone --depth=1  --single-branch -b ${this.task.buildInfo.gitBranch} ${
            this.task.getGitUserAndPasswordUrl(
                gitServer
            )
        } code

'''
"""
    } else if (gitServer.accessToken.HasValue) {

        var at = "";

        if (gitServer.gitServerType == GitServerTypeEnum.Gitlab) {
            at = "x-access-token:" + gitServer.accessToken
        } else {
            at = gitServer.accessToken;
        }

        return """
sh '''#!/usr/bin/env bash
git clone --depth=1  --single-branch -b ${this.task.buildInfo.gitBranch} ${
            this.task.getAccessTokenUrl(at)
        }  code
'''
"""
    }
    throw RuntimeException("gitData 没有配置 accessToken !")
}


